import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import {getLoginUser} from "../api/userController";

// 从localStorage恢复用户状态
const getStoredUser = () => {
  try {
    const storedUser = localStorage.getItem('loginUser')
    if (storedUser) {
      return JSON.parse(storedUser)
    }
  } catch (error) {
    console.error('从localStorage获取用户信息失败:', error)
  }
  return { userName: '未登录' }
}

// 保存用户状态到localStorage
const saveUserToStorage = (user: API.LoginUserVO) => {
  try {
    localStorage.setItem('loginUser', JSON.stringify(user))
  } catch (error) {
    console.error('保存用户信息到localStorage失败:', error)
  }
}

// 清除localStorage中的用户状态
const clearUserFromStorage = () => {
  try {
    localStorage.removeItem('loginUser')
  } catch (error) {
    console.error('清除localStorage中的用户信息失败:', error)
  }
}

export const useLoginUserStore = defineStore('loginUser', () => {
  // 从localStorage初始化用户状态
  const loginUser = ref<API.LoginUserVO>(getStoredUser())

  // 获取登录用户信息
  async function fetchLoginUser() {
    try {
      const res = await getLoginUser()
      if (res.data.code === 0 && res.data.data) {
        loginUser.value = res.data.data
        // 保存到localStorage
        saveUserToStorage(res.data.data)
        return true
      }
      return false
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return false
    }
  }

  // 设置登录用户
  function setLoginUser(newLoginUser: API.LoginUserVO) {
    loginUser.value = newLoginUser
    // 保存到localStorage
    saveUserToStorage(newLoginUser)
  }

  // 登出
  function logout() {
    loginUser.value = { userName: '未登录' }
    // 从localStorage清除
    clearUserFromStorage()
  }

  // 检查登录状态
  const isLoggedIn = computed(() => {
    return loginUser.value.userName !== '未登录' && loginUser.value.userName !== undefined && loginUser.value.id !== undefined
  })

  return {
    loginUser,
    fetchLoginUser,
    setLoginUser,
    logout,
    isLoggedIn
  }
})